<?php
/**
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2020/1/14
 * Time: 10:11
 */

namespace app\forum\model;

use app\common\exception\ApiError;
use think\model\concern\SoftDelete;

/**
 * @method hasMany(string $string, string $string1)
 * @method belongsTo(string $string)
 */
class Post extends ForumBase
{
    use SoftDelete;
    /**
     * 一对一获取用户信息
     * @return mixed
     */
    public function user()
    {
        return $this->belongsTo("user");
    }

    // 一对多
    public function images()
    {
        return $this->hasMany("PostImages", "post_id")
            ->field("id,post_id,path");
    }

    // 一对多
    public function comments()
    {
        return $this->hasMany("PostComment", "post_id");
    }

    // 一对多
    public function likes()
    {
        return $this->hasMany("PostLike", "post_id");
    }

    // 帖子封面图
    public function getCoverAttr($value, $data)
    {
        $cover = "";
        switch ($data["post_type"]) {
            case 1 :
                $cover = PostImages::where("post_id", $data["id"])->value("path");
                break;
            case 2 :
                $cover = attach($data["video"] . ".jpeg");
                break;
        }
        return $cover ? attach($cover) : "";
    }

    // 点赞数
    public function getLikesCountAttr($value, $data)
    {
        return $data["extra_like_count"] + $value;
    }

    /**
     * 帖子详情
     * @param $input
     * @return \think\db\Query|null
     * @throws ApiError
     * @throws \think\Exception\DbException
     */
    public static function getInfo($input)
    {
        // 最热前 3 条评论
        $comments = function ($q) {
            $q->with(["user"])->withCount(["likes"])
                ->orderRaw("likes_count + extra_like_count desc,create_time desc")
                ->limit($params["comments_nums"] ?? 3)
                ->visible(["id", "create_time", "content", "likes_count", "user"]);
        };

        // 查询
        $post = self::with(["user", "images", "comments" => $comments])
            ->withCount(["likes", "comments"])
            ->get($input["post_id"]);

        if (!$post) throw new ApiError("content_not_found");

        $post->is_like = PostLike::isliked($input["post_id"], $input["user_id"], 1);

        return $post->append(["cover"]);
    }

    // 获取 bbs 列表
    public static function getLists($params)
    {
        // TODO::应重封装按权排..
        $order = 'create_time desc';
        if (isset($params["order"])) {
            $params["order"] == "hot"  && $order = 'create_time desc';
            $params["order"] == "hot"  && $order = 'likes_count + extra_like_count desc';
            $params["order"] == "rand" && $order = 'rand()';
        }

        // 筛选
        $where = $params["where"] ?? [];

        $params["limit"] = $params["limit"] ?? 5;
        $result = self::with(["user", "images"])
            ->withCount(["likes", "comments"])
            ->orderRaw($order)
            ->lists($params)
            ->where($where)
            ->all(["status" => 1])
            ->append(["cover"])
            ->hidden(["extra_like_count", "delete_time"])
            ->each(function ($item, $key) use ($params) {
                $item->is_like = PostLike::isliked($item->id
                    , $params["user_id"], 1);
                $item->user->relation = UserFans::relationship(
                    $params["user_id"], $item->user_id);
            });

        return $result;
    }
}